<template>
  <el-card class="position-list-card">
    <h2>岗位浏览</h2>
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="关键词">
        <el-input v-model="searchForm.keyword" placeholder="岗位名称/职责/要求" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchPositions">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="positions" stripe border class="position-table" v-loading="loading">
      <el-table-column prop="positionName" label="岗位名称" min-width="120" />
      <el-table-column label="企业名称" min-width="120">
        <template #default="{ row }">
          <el-link type="primary" @click="showEnterprise(row)">{{ row.enterpriseName || row.enterpriseDetail?.enterpriseName || '点击查看' }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="salaryRange" label="薪资范围" min-width="100" />
      <el-table-column prop="workLocation" label="工作地点" min-width="100" />
      <el-table-column prop="recruitmentNum" label="招聘人数" min-width="80" />
      <el-table-column prop="responsibility" label="岗位职责" min-width="200">
        <template #default="{ row }">
          <div style="white-space: pre-line;">{{ row.responsibility }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="requirement" label="任职要求" min-width="200">
        <template #default="{ row }">
          <div style="white-space: pre-line;">{{ row.requirement }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="openApply(row)">投递简历</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="showDialog" title="企业详情" width="500px">
      <el-descriptions v-if="currentDetail" :column="1" border>
        <el-descriptions-item label="企业名称">{{ currentDetail.enterpriseName }}</el-descriptions-item>
        <el-descriptions-item label="所属行业">{{ currentDetail.industry }}</el-descriptions-item>
        <el-descriptions-item label="企业规模">{{ currentDetail.scale }}</el-descriptions-item>
        <el-descriptions-item label="企业地址">{{ currentDetail.address }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentDetail.contact }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
    <el-dialog v-model="showApplyDialog" title="投递简历" width="400px">
      <el-form :model="applyForm" label-width="80px">
        <el-form-item label="备注">
          <el-input v-model="applyForm.remark" type="textarea" placeholder="可选" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showApplyDialog = false">取消</el-button>
        <el-button type="primary" @click="submitApplication" :loading="applyLoading">确定投递</el-button>
      </template>
    </el-dialog>
    <div class="pagination-bar">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="searchForm.size"
        :current-page="searchForm.page"
        @current-change="onPageChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const searchForm = ref({ keyword: '', page: 1, size: 10 }) // 只保留 keyword
const positions = ref([])
const total = ref(0)
const loading = ref(false)
const showDialog = ref(false)
const currentDetail = ref(null)
const enterpriseCache = ref({})
const showApplyDialog = ref(false)
const applyForm = ref({ remark: '' })
const applyLoading = ref(false)
const currentPositionId = ref(null)
const allPositions = ref([])

const fetchEnterpriseDetail = async (id) => {
  if (enterpriseCache.value[id]) return enterpriseCache.value[id]
  try {
    const res = await axios.get(`/enterprise/info/${id}`)
    enterpriseCache.value[id] = res.data || res
    return enterpriseCache.value[id]
  } catch (e) { return {} }
}

const fetchPositions = async () => {
  loading.value = true
  try {
    const params = { ...searchForm.value }
    Object.keys(params).forEach(key => { if (!params[key]) delete params[key] })
    // 不传分页参数，获取全部
    delete params.page
    delete params.size
    const res = await axios.get('/position/search', { params })
    const data = res.data || res
    allPositions.value = data.list || []
    total.value = allPositions.value.length
    // 默认显示第一页
    const start = (searchForm.value.page - 1) * searchForm.value.size
    const end = start + searchForm.value.size
    positions.value = allPositions.value.slice(start, end)
    for (const row of positions.value) {
      if (!row.enterpriseName && row.enterpriseId) {
        const detail = await fetchEnterpriseDetail(row.enterpriseId)
        row.enterpriseDetail = detail
        if (detail.enterpriseName) row.enterpriseName = detail.enterpriseName
      }
    }
  } catch (e) {}
  loading.value = false
}
const resetSearch = () => {
  searchForm.value = { keyword: '', degree: '', major: '', page: 1, size: 10 }
  fetchPositions()
}
const onPageChange = page => {
  searchForm.value.page = page
  // 只切片，不重新请求
  const start = (searchForm.value.page - 1) * searchForm.value.size
  const end = start + searchForm.value.size
  positions.value = allPositions.value.slice(start, end)
}
const showEnterprise = async (row) => {
  currentDetail.value = row.enterpriseDetail || await fetchEnterpriseDetail(row.enterpriseId)
  showDialog.value = true
}
const openApply = (row) => {
  currentPositionId.value = row.id
  applyForm.value = { remark: '' }
  showApplyDialog.value = true
}
const submitApplication = async () => {
  applyLoading.value = true
  try {
    await axios.post('/applications/submit', {
      positionId: currentPositionId.value,
      remark: applyForm.value.remark
    })
    showApplyDialog.value = false
    applyForm.value = { remark: '' }
    currentPositionId.value = null
    ElMessage.success('投递成功！')
  } catch (e) {}
  applyLoading.value = false
}
onMounted(() => {
  fetchPositions()
})
</script>

<style scoped>
.position-list-card {
  max-width: 1100px;
  margin: 40px auto;
  padding: 30px 20px;
}
.search-form {
  margin-bottom: 20px;
}
.position-table {
  margin-bottom: 20px;
}
.pagination-bar {
  text-align: right;
  margin-top: 10px;
}
</style> 